﻿function Install-SharePoint
{
    <# 
     .Synopsis
      Launches the SharePoint Installer.

     .Description
      This script launches the SharePoint Installer

     .Parameter ProductKey
      The SharePoint Product Key

     .Parameter TargetInstallDirectory
      The target installation directory
      The default value for this parameter is 'C:\Program Files\Microsoft Office Servers\'      

     .Parameter TargetDataDirectory
      The SharePoint Product Key
      The default value for this parameter is 'C:\Program Files\Microsoft Office Servers\15.0\Data\'      

     .Parameter PathToSpInstallFiles
      The full file system path where the installation source files for SharePoint 2013 are located. 
      The default value for this parameter is 'C:\ProgramData\SharePoint Total Automation Toolkit\Software\04-SharePointServer2013'      

     .Example
       Install-SharePoint -ProductKey N3MDM-DXR3H-JD7QH-QKKCR-BY2Y7

     .Example
       Install-SharePoint -ProductKey N3MDM-DXR3H-JD7QH-QKKCR-BY2Y7 -PathToSpInstallFiles 'C:\ProgramData\SharePoint Total Automation Toolkit\Software\04-SharePointServer2013'       

    #>
    [CmdletBinding(DefaultParametersetName="CustomPaths")]
    param([parameter(ParameterSetName = "CustomPaths", 
                     Mandatory = $false,
                     HelpMessage = "The full file system path where the installation source files for SharePoint are located. The default value for this parameter is 'C:\ProgramData\SharePoint Total Automation Toolkit\Software\04-SharePointServer2013'")]
                     [string]$PathToSpInstallFiles = ($env:ProgramData + "\SharePoint Total Automation Toolkit\Software\04-SharePointServer2013"),
          [parameter(ParameterSetName = "CustomPaths", 
                     Mandatory = $true,
                     HelpMessage = "The SharePoint Product Key")]
          [parameter(ParameterSetName = "DefaultPaths", 
                     Mandatory = $true,
                     HelpMessage = "The SharePoint Product Key")]
                     [string]$ProductKey,
          [parameter(ParameterSetName = "CustomPaths", 
                     Mandatory = $false,
                     HelpMessage = "The target installation directory")]
          [parameter(ParameterSetName = "DefaultPaths", 
                     Mandatory = $false,
                     HelpMessage = "The target installation directory")]
                     [string]$TargetInstallDirectory = "C:\Program Files\Microsoft Office Servers\",
          [parameter(ParameterSetName = "CustomPaths", 
                     Mandatory = $false,
                     HelpMessage = "The target installation directory")]
          [parameter(ParameterSetName = "DefaultPaths", 
                     Mandatory = $false,
                     HelpMessage = "The target installation directory")]
                     [string]$TargetDataDirectory = "C:\Program Files\Microsoft Office Servers\15.0\Data\")

    switch ($PSCmdlet.ParameterSetName)
    {
        "CustomPaths"
        {
            $Restart = $false
        }    
        default
        {
            $Restart = $false
        }    
    }

	$rebootStatus = Get-PendingReboot
	if ($rebootStatus.RebootPending -eq $true)
	{
		Write-Host "NOTE: A system restart is required. Please restart the system prior to continuing with the SharePoint installation." -ForegroundColor Yellow
		Write-Host "      When the system restarts please rerun this script until you no longer receive a restart request." -ForegroundColor Yellow
		throw 
	}

    # Initialize Progress Variables
    [int]$progressBarId = 100
    $startTime = [System.DateTime]::Now

    Write-Host "Beginning the SharePoint installation."

        [System.Xml.XmlDocument]$currentConfigXml = 
        @"
<Configuration>
    <Logging Type="verbose" Path="%temp%" Template="SharePoint Server Setup(*).log"/>
    <PIDKEY Value="Enter PID Key Here" />
    <Display Level="none" CompletionNotice="no" AcceptEula="no" SuppressModal="yes" NoCancel="yes"/>
    <Setting Id="SERVERROLE" Value="APPLICATION"/>
    <Setting Id="USINGUIINSTALLMODE" Value="0"/>
    <Setting Id="SETUP_REBOOT" Value="Never" />
    <Setting Id="SETUPTYPE" Value="CLEAN_INSTALL"/>
    <INSTALLLOCATION Value="C:\Program Files\Microsoft Office Servers\" />
    <DATADIR Value="C:\Program Files\Microsoft Office Servers\15.0\Data\" />
</Configuration>
"@

    $currentConfigXml.Configuration.PIDKEY.Value = $ProductKey
    $currentConfigXml.Configuration.INSTALLLOCATION.Value = $TargetInstallDirectory
    $currentConfigXml.Configuration.DATADIR.Value = $TargetDataDirectory

    # Save the newly generated config.xml file to the local temp directory
    $configXmlName = ("config_{0}.xml" -f (Get-Date -Format 'yyyy_MMM_dd_HH_mm_ss') )
    $configXmlPath = Join-Path $env:temp $configXmlName
    $currentConfigXml.Save($configXmlPath)


    #region Task 1

    # Launch the SharePoint Prerequisite Installer
    $setupExe = ($PathToSpInstallFiles + "\setup.exe")
    $setupArgs = ("/config {0}" -f $configXmlPath)
    $setupExeInstance = [System.Diagnostics.Process]::Start($setupExe, $setupArgs)
    $step = 5
    $value = 0

    while (-not ($setupExeInstance.HasExited)){
        $currentRuntime = [System.DateTime]::Now - $startTime
        Write-Progress -Id $progressBarId -Activity "Installing SharePoint" -PercentComplete ($value+=$step) -CurrentOperation "Executing the SharePoint Installation Wizard" -Status ("The current operation has been running for {0}:{1}:{2}" -f $currentRuntime.Hours.ToString("00"), $currentRuntime.Minutes.ToString("00"), $currentRuntime.Seconds.ToString("00"))
     
        if ($value -ge 100) { $value = 0}

        Start-Sleep -Seconds 1
    }

    if ($setupExeInstance.ExitCode -eq 0)
    {
        Write-Host "     SharePoint Successfully Installed"
    }
    elseif ($setupExeInstance.ExitCode -eq 3010)
    {
        if ($Restart -eq $true)
        {
            Restart-Computer
        }
        else
        {
            Write-Host "NOTE: Setup is complete, however a system restart is required. Please restart the system prior to continuing with the SharePoint installation." -ForegroundColor Yellow
        }
    }
    elseif ($setupExeInstance.ExitCode -eq 30066)
    {
		$exitCode = $setupExeInstance.ExitCode
        Write-Host "     Installation of SharePoint Failed a prerequisite check with exit code ($exitCode)" -ForegroundColor Red
		Write-Host "     This can be caused by a pending restart that is blocking installation." -ForegroundColor Red
		Write-Host "     Check the installation log file for details. The log file is located at" -ForegroundColor Red
		write-Host "     $env:TMP\SharePoint Server Setup(<datetime>).log" -ForegroundColor Red
        throw
	}
    else
    {
		$exitCode = $setupExeInstance.ExitCode
        Write-Host "     Installation of SharePoint Failed with exit code ($exitCode)" -ForegroundColor Red
		Write-Host "     Check the installation log file for details. The log file is located at" -ForegroundColor Red
		write-Host "     $env:TMP\SharePoint Server Setup(<datetime>).log" -ForegroundColor Red
        throw
    }

    #endregion

    Write-Progress -Id $progressBarId -Activity "Installing SharePoint" -Status "Finishing" -PercentComplete 100 -CurrentOperation "" -Completed

    Write-Host "SharePoint installation complete."
    
}